package org.mch.start;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class MDebugDLG extends JDialog {
	private static final long serialVersionUID = -2712541381113667908L;

	private final JPanel contentPanel = new JPanel();

	private JTextArea textArea;

	private MDebugDLG() {
		super();
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new BorderLayout(0, 0));
		{
			JScrollPane scrollPane = new JScrollPane();
			contentPanel.add(scrollPane, BorderLayout.CENTER);
			{
				scrollPane.setViewportView(getTextArea());
			}
		}
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("清除");
				okButton.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent e) {
						getTextArea().setText("");
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}

	public JTextArea getTextArea() {
		if (textArea == null) {
			this.textArea = new JTextArea();
			this.textArea.setFont(new Font("宋体", 0, 14));
			this.textArea.setBorder(new EtchedBorder(0, null, null));
		}
		return textArea;
	}

	@Override
	public void setVisible(boolean b) {
		super.setVisible(b);
	}

	public static void debug(Object obj) {
		String str = null;
		if (obj instanceof String) {
			str = (String) obj;
		} else {
			str = obj.toString();
		}

		PlainDocument textdoc = (PlainDocument) dlg.getTextArea().getDocument();
		try {
			textdoc.insertString(textdoc.getLength(), "\n" + str, null);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}

	private static MDebugDLG dlg = new MDebugDLG();

	public static MDebugDLG getInstance() {
		return dlg;
	}
}
